package com.sfac.springCloudTest.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sfac.common.vo.Result;
import com.sfac.common.vo.Search;
import com.sfac.springCloudTest.dao.CityDao;
import com.sfac.springCloudTest.service.CityService;
import com.sfac.test.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * City Service Impl
 */
@Service
public class CityServiceImpl implements CityService {

	@Autowired
	private CityDao cityDao;
	@Value("${server.port}")
	private int port;

	@Override
	@Transactional
	public Result<City> insertCity(City city) {
		City temp = cityDao.getCityByCityName(city.getCityName());
		if (temp != null) {
			return new Result<>(Result.ResultStatus.FAILED.code, "城市名重复.");
		}

		city.setDateModified(LocalDateTime.now());
		city.setDateCreated(LocalDateTime.now());

		cityDao.insertCity(city);
		return new Result<>(Result.ResultStatus.SUCCESS.code, "插入成功.", city);
	}

	@Override
	@Transactional
	public Result<City> updateCity(City city) {
		City temp = cityDao.getCityByCityName(city.getCityName());
		if (temp != null && temp.getCityId() != city.getCityId()) {
			return new Result<>(Result.ResultStatus.FAILED.code, "城市名重复.");
		}

		city.setDateModified(LocalDateTime.now());

		cityDao.updateCity(city);
		return new Result<>(Result.ResultStatus.SUCCESS.code, "修改成功.", city);
	}

	@Override
	@Transactional
	public Result<Object> deleteCityByCityId(int cityId) {
		cityDao.deleteCityByCityId(cityId);
		return new Result<>(Result.ResultStatus.SUCCESS.code, "删除成功.");
	}

	@Override
	public City getCityByCityId(int cityId) {
		System.err.println(String.format("======================== port: %d ====================", port));
		return cityDao.getCityByCityId(cityId);
	}

	@Override
	public List<City> getCitiesByCountryId(int countryId) {
		return Optional
				.ofNullable(cityDao.getCitiesByCountryId(countryId))
				.orElse(Collections.emptyList());
	}

	@Override
	public PageInfo<City> getCitiesBySearch(Search search) {
		search.init();
		PageHelper.startPage(search.getCurrentPage(), search.getPageSize());
		return new PageInfo<City>(Optional
				.ofNullable(cityDao.getCitiesBySearch(search))
				.orElse(Collections.emptyList()));
	}

	@Override
	@Transactional
	public Result<Object> insertBatchCities(List<City> cities) {
		cities.stream().forEach(item -> {
			item.setDateModified(LocalDateTime.now());
			item.setDateCreated(LocalDateTime.now());
		});

		cityDao.insertBatchCities(cities);
		return new Result<>(Result.ResultStatus.SUCCESS.code, "批量插入成功.");
	}
}
